package com.we823.project.repository.service.sys;

import java.util.Date;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.we823.project.common.web.status.LogType;
import com.we823.project.model.sys.LogModel;
import com.we823.project.repository.dao.sys.LogRepository;
import com.we823.project.repository.service.AbstractBaseService;

@Service("logService")
public class LogService extends AbstractBaseService<LogModel> {

	private LogRepository logRepository;
	
	@Autowired
	public LogService(LogRepository logRepository) {
		super(logRepository);
		this.logRepository=logRepository;
	}
	
	public void loginSuccess(String username) {
		LogModel logModel = new LogModel();
		logModel.setAddtime(new Date());
		logModel.setName(username+"登录成功");
		logModel.setType(LogType.LoginSuccess.name());
		logModel.setDescription(username+"登录成功");
		logModel.setInputer(username);
		logRepository.save(logModel);
	}
	
	public void loginFailure(String username) {
		LogModel logModel = new LogModel();
		logModel.setAddtime(new Date());
		logModel.setName(username+"登录失败");
		logModel.setType(LogType.LoginFailure.name());
		logModel.setDescription(username+"登录失败");
		logModel.setInputer(username);
		logRepository.save(logModel);
	}
	
	public void noAuthorition(String message,Exception ex) {
		LogModel logModel = new LogModel();
		logModel.setAddtime(new Date());
		logModel.setName(message);
		logModel.setType(LogType.NoAuthorition.name());
		logModel.setDescription(message+":"+ex.getMessage());
		logModel.setInputer("");
		logRepository.save(logModel);
	}
	
	public void saveLog(String message,String code,Exception ex) {
		LogModel logModel = new LogModel();
		logModel.setAddtime(new Date());
		logModel.setName(message);
		logModel.setType(LogType.parse(code).name());
		if(ex!=null) {
			logModel.setDescription(message+":"+ex.getMessage());
		}else {
			logModel.setDescription(message);
		}
		org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject();
		String inputer = "";
		if(subject!=null) {
			inputer = (String) subject.getPrincipal();
		}
		logModel.setInputer(inputer);
		logRepository.save(logModel);
	}

}
